package com.zzg.srb.oss.controller;

import com.zzg.srb.common.exception.BusinessException;
import com.zzg.srb.common.result.R;
import com.zzg.srb.common.result.ResponseEnum;
import com.zzg.srb.oss.service.FileService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.io.InputStream;

/**
 * @Author zhengzg
 * @Date 2022/6/5 9:48
 * @Version 1.0
 */
@Api(tags = "oss文件管理")
@RestController
@RequestMapping("/api/oss/file")
public class FileController {

    private Logger log = LoggerFactory.getLogger(FileController.class);

    @Resource
    private FileService fileService;

    @ApiOperation("文件上传")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "文件",name = "file",dataType = "文件",required = true),
            @ApiImplicitParam(value = "模块",name = "module",dataType = "String",required = true)
    })
    @PostMapping("/upload")
    public R upload(@RequestParam("file") MultipartFile file,String moudle){
        try {
            InputStream fileInputStream = file.getInputStream();
            String url = fileService.upload(fileInputStream, moudle, file.getOriginalFilename());
            return R.ok().message("文件上传成功").data(url);
        } catch (IOException e) {
            throw new BusinessException(ResponseEnum.UPLOAD_ERROR,e);
        }
    }

    @ApiOperation("文件删除")
    @ApiImplicitParam(value = "图片路径",name = "url",dataType = "String",required = true)
    @DeleteMapping("/remove")
    public R remove(@RequestParam("url") String url){
        fileService.removeFile(url);
        return R.ok().message("文件删除成功");
    }
}
